package com.ror.java.se.reflect;

import java.io.*;
import java.lang.reflect.Field;

public class Demo05 {
    public static void main(String[] args) throws IllegalAccessException, IOException {
        Teacher tea1 = new Teacher("李四", 12000);
        Student stu1 = new Student("张三", 25, "男");
        saveObject(tea1);
        saveObject(stu1);
    }

    private static void saveObject(Object o) throws IllegalAccessException, IOException {
        Class<?> c = o.getClass();
        Field[] fields = c.getDeclaredFields();
        StringBuilder dataBuilder = new StringBuilder();
        BufferedWriter bw = new BufferedWriter(
                new FileWriter("assets" + File.separator + "reflect"
                        + File.separator + "save-" + o.hashCode() + ".txt")
        );
        for (Field field : fields) {
            field.setAccessible(true);
            dataBuilder.append(field.getName()).append("=").append(field.get(o));
            bw.write(dataBuilder.toString());
            bw.newLine();
            dataBuilder.setLength(0);
        }
        bw.flush();
        bw.close();
    }
}
